//
//  BIZContractVC.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/24.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZContractVC.h"
#import "BIZContractCell.h"
#import "BIZContractModel.h"
#import "BIZContractDetailVC.h"
#import "BIZContractEditVC.h"

@interface BIZContractVC ()
@property (nonatomic, strong) NSMutableArray *contractsArr;
/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger lastId;
@end

@implementation BIZContractVC

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    DeLog(@"++++++++");
    [self setupNavBar];
    [self setupTableView];
    [self getNewContractsListData];
   
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNewContractsListData) name:kReloadContractListNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.contractsArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BIZContractCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZContractCell" forIndexPath:indexPath];
    cell.contractModel = self.contractsArr[indexPath.section];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BIZContractModel *model = self.contractsArr[indexPath.section];
    BIZContractDetailVC *vc = [[BIZContractDetailVC alloc]init];
    vc.uuid = model.uuid;
    MPWeakSelf(self);
    
    vc.didClickReturnBlock = ^(){
        model.redType = @"0";
        [weakself.tableView reloadSections:[[NSIndexSet alloc]initWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    };
    
    vc.compeleteServiceReturnBlock = ^(){
        model.status = @"4";
        [weakself.tableView reloadSections:[[NSIndexSet alloc]initWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
    };
    
    
    
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)getContractsListData
{
    
//    {
//        "pageIndex":1,
//        "pageEnd":3
//    }

    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"pageIndex"] = @(self.lastId);
    dic[@"pageEnd"] = @(self.lastId+9);
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kContrctListUrl parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject+++++:%@",responseObject);
        [MBProgressHUD  hideHUD];
        [self stopRefresh];
        BIZContractListModel *model = [BIZContractListModel yy_modelWithJSON:responseObject];
        if (model.code == 1) {
            [self.contractsArr addObjectsFromArray:model.contractModelArr];
            self.lastId += model.contractModelArr.count;
            [self.tableView reloadData];
        } else {
            [MBProgressHUD showErrorMessage:model.des];
            if (model.code == 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccessBlock = ^(){
                    [weakself getNewContractsListData];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        [self stopRefresh];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
    
}



- (void)getNewContractsListData
{
    self.lastId = 1;
    [self.contractsArr removeAllObjects];
    [self getContractsListData];
}

- (void)getMoreContractsListData
{
    [self getContractsListData];
}



- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}


-(void)setupNavBar
{
    self.title = @"合同审核";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"我要审合同" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
}


- (void)rightBarButtonItemClick
{
    BIZContractEditVC *vc = [[BIZContractEditVC alloc]init];
    MPWeakSelf(self);
    vc.commitContractReturnBlock = ^(){
//        [UIAlertController showAlertViewWithTitle:@"您的合同审核要求已提交，请耐心等待咨询师回复"
//                                          message:nil
//                                cancelButtonTitle:@"关闭"
//                               confirmButtonTitle:nil
//                                      cancelBlock:nil
//                                     confirmBlock:nil];
        [weakself getNewContractsListData];
        
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupTableView
{
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.sectionHeaderHeight = 10;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(11-35, 0, 0, 0);
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getNewContractsListData)];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreContractsListData)];
}


- (NSMutableArray *)contractsArr
{
    if (!_contractsArr) {
        _contractsArr = [NSMutableArray array];
    }
    
    return _contractsArr;
}

- (NSInteger)lastId
{
    if (!_lastId) {
        _lastId = 1;
    }
    
    return _lastId;
}

@end
